package com.tgjorgoski.utils;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;

import javax.swing.*;
import javax.swing.event.PopupMenuEvent;
import javax.swing.text.Caret;
import javax.swing.text.JTextComponent;

public class DropDownColorButton extends DropDownButton implements Icon {
	JPopupMenu popupMenu;
	private Color color= Color.RED;
	private ColorToolbar colorToolbar;
	private JTextComponent editor;
	
	public DropDownColorButton(JTextComponent editor) {
		this.editor=editor;
		colorToolbar=new ColorToolbar();
		popupMenu = ViewUtils.createAndTrackPopupMenu();
		popupMenu.add(colorToolbar);
		popupMenu.addPopupMenuListener(this);
		colorToolbar.addPropertyChangeListener(ColorToolbar.COLOR_PROPERTY, this);
		setIcon(this);
	}

	protected JPopupMenu getPopupMenu() {
    	return popupMenu;
    }

	public int getIconHeight() {
		return 20;
	}

	public int getIconWidth() {
		return 13;
	}
	
	Font defFont = new Font("Arial",Font.BOLD+Font.ITALIC, 18);
	Color defColor = new Color(0,0,50);
	public void paintIcon(Component c, Graphics g, int x, int y) {
		Color old = g.getColor();
		Font oldFont = g.getFont();
		setFont(defFont);
		g.setColor(Color.BLACK);
		g.drawString("A", x, y+15);
		g.setColor(color);
		g.fillRect(x, y+17, 15, 3);
		g.setColor(old);
		g.setFont(oldFont);
	}
	
    public void propertyChange(PropertyChangeEvent evt) {
    	if (evt.getPropertyName().equals(ColorToolbar.COLOR_PROPERTY)) {
    		if (evt.getNewValue() instanceof Color) {
        		Color newColor = (Color)evt.getNewValue();
        		color=newColor;
        		popupMenu.setVisible(false);
        		invalidate();
        		repaint();
        		SwingUtilities.invokeLater(new Runnable() {
				
					public void run() {
		        		fireActionPerformed(new ActionEvent(this,MouseEvent.MOUSE_CLICKED,""));
					}
				
				});
    		}
    	} else {
    		super.propertyChange(evt);
    	}
    }
    
    public Color getColor() {
    	return color;
    }

    public void popupMenuWillBecomeVisible(PopupMenuEvent e){
        super.popupMenuWillBecomeVisible(e);
        Caret caret = editor.getCaret();
        caret.setVisible(true);
        caret.setSelectionVisible(true);
    }
}
